package net.wofly.common.service.impl;

import net.wofly.common.service.IUploadService;
import net.wofly.common.util.FileTypeAddress;
import net.wofly.common.util.Identities;
import net.wofly.common.util.ResultCode;
import net.wofly.common.util.ReturnBean;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * 上传文件
 *
 * @author siqingwei
 * @date 2018/3/11
 */
@Service("iUploadService")
public class UploadServiceImpl implements IUploadService {
    @Override
    public ReturnBean<String> uploadSingleFile(Integer fileType, MultipartFile file, String path) {
        LocalDate today = LocalDate.now();
        String address = FileTypeAddress.getAddress(fileType);
        String targetPath = address + File.separator + today.getYear() + File.separator + today.getMonthValue();
        if (fileType.equals(FileTypeAddress.商品图片.getValue())) {
            targetPath = address;
        }
        String fileName = Identities.uuid2() + "." +file.getOriginalFilename().split("\\.")[1];
        String relativePath = targetPath + File.separator + fileName;
        String $file = path + relativePath;
        File uploadedFile = new File($file);
        if(uploadedFile == null){
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "targetFile is not be null");
        }
        File f= new File(uploadedFile.getParent());
        if(!f.exists()){
            f.mkdirs();
        }

        try {
            FileCopyUtils.copy(file.getBytes(), uploadedFile);
        } catch (IOException e) {
            e.printStackTrace();
            return new ReturnBean<>(ResultCode.ERROR_SERVICE,"上传文件："+ file.getOriginalFilename() +"时，出错！");
        }
        return new ReturnBean<>(ResultCode.SUCCESS, "上传单个文件成功！", relativePath);
    }

    @Override
    public ReturnBean<List<String>> uploadBatchFiles(Integer fileType, MultipartFile[] files, String path) {

        LocalDate today = LocalDate.now();
        String address = FileTypeAddress.getAddress(fileType);
        String targetPath = address + File.separator + today.getYear() + File.separator + today.getMonthValue();
        if (fileType.equals(FileTypeAddress.商品图片.getValue())) {
            targetPath = address;
        }

        List<String> relativePathList = new ArrayList<>(files.length);

        for (MultipartFile file : files) {
            String fileName = Identities.uuid2() + "." +file.getOriginalFilename().split("\\.")[1];
            String relativePath = targetPath + File.separator + fileName;
            String $file = path + relativePath;
            File uploadedFile = new File($file);
            if(uploadedFile == null){
                return new ReturnBean<>(ResultCode.ERROR_SERVICE, "targetFile is not be null");
            }
            File f= new File(uploadedFile.getParent());
            if(!f.exists()){
                f.mkdirs();
            }

            try {
                FileCopyUtils.copy(file.getBytes(), uploadedFile);
                relativePathList.add(relativePath);
            } catch (IOException e) {
                e.printStackTrace();
                return new ReturnBean<>(ResultCode.ERROR_SERVICE,"上传文件："+ file.getOriginalFilename() +"时，出错！");
            }
        }

        return new ReturnBean<>(ResultCode.SUCCESS, "上传多个文件成功！", relativePathList);
    }

    @Override
    public ReturnBean<String> uploadSingleFileForBase64(Integer fileType, String fileBase64, String path) {
        // 通过base64来转化图片
        fileBase64 = fileBase64.replaceAll("data:image/jpeg;base64,", "");
        BASE64Decoder decoder = new BASE64Decoder();
        // Base64解码
        byte[] imageByte = null;
        try {
            imageByte = decoder.decodeBuffer(fileBase64);
            for (int i = 0; i < imageByte.length; ++i) {
                // 调整异常数据
                if (imageByte[i] < 0) {
                    imageByte[i] += 256;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        LocalDate today = LocalDate.now();
        String address = FileTypeAddress.getAddress(fileType);
        String targetPath = address + File.separator + today.getYear() + File.separator + today.getMonthValue();
        if (fileType.equals(FileTypeAddress.商品图片.getValue())) {
            targetPath = address;
        }
        String fileName = Identities.uuid2() + "." + "jpg";
        String relativePath = targetPath + File.separator + fileName;
        String $file = path + relativePath;
        File uploadedFile = new File($file);
        if(uploadedFile == null){
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "targetFile is not be null");
        }

        File f= new File(uploadedFile.getParent());
        if(!f.exists()){
            f.mkdirs();
        }

        try {
            FileCopyUtils.copy(imageByte, uploadedFile);
        } catch (IOException e) {
            e.printStackTrace();
            return new ReturnBean<>(ResultCode.ERROR_SERVICE,"上传单个文件出错！");
        }
        return new ReturnBean<>(ResultCode.SUCCESS, "上传单个文件成功！", relativePath);
    }
}
